package com.norther.official.core.service.impl;

import java.util.Date;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.norther.official.common.util.DateUtils;
import com.norther.official.core.dao.BannerRepository;
import com.norther.official.core.dao.specifications.BannerSpecifications;
import com.norther.official.core.entity.Banner;
import com.norther.official.core.service.IBannerService;

@Service
@Transactional(readOnly = true)
public class BannerService implements IBannerService {

	@Resource
	private BannerRepository bannerRepository;
	private static final Sort ORDER_BY_SORT = new Sort(new Order(Direction.ASC,
			"sort"));

	@Override
	public Page<Banner> pageQuery(Pageable pageable) {

		pageable.getSort().and(ORDER_BY_SORT);

		Page<Banner> page = bannerRepository.findAll(
				BannerSpecifications.bannerListQueryCriteria(null), pageable);
		return page;
	}

	@Override
	public Banner findBannerById(Long id) {
		return bannerRepository.findOne(id);
	}

	@Transactional
	@Override
	public void saveBanner(Banner banner) {
		Date now = DateUtils.getNowDateTime();
		banner.setUpdateTime(now);
		banner.setIsDelete(0);

		Long id = banner.getId();
		if (id == null) {
			banner.setCreateTime(now);
			bannerRepository.save(banner);
		} else {
			Banner temp = findBannerById(id);
			temp.setLink(banner.getLink());
			temp.setPath(banner.getPath());
			temp.setSort(banner.getSort());
			temp.setTitle(banner.getTitle());
			temp.setUpdateTime(banner.getUpdateTime());

			bannerRepository.save(temp);
		}
	}

	@Transactional
	@Override
	public int deleteBannersByIds(Long[] ids) {
		return bannerRepository.deleteByIdIn(ids);
	}

}
